<?php
/**
 * 用户信息模块
 * 2019.3.12
 * xiaosu
 */
namespace app\api\controller;

use app\api\service\UserService;
use app\api\service\RegisterService;
use app\api\validate\CardValidate;
use think\Db;

class UserController extends BaseController
{
	public $UserService;

	public function __construct()
	{
		$this->checkUser();
		$this->UserService = new UserService();
	}
	/**
	 * 设置支付密码
	 */
	public function setPayPassword()
	{
		$pay_password = input('pay_password');
		$second_password = input('second_password');

		if (!preg_match("/^\d{6}$/", $pay_password)) {
			$this->ApiResult(false,10001,'请输入6位支付密码');
		}

		if ($pay_password !== $second_password) {
			$this->ApiResult(false,10001,'两次密码必须一样');
		}

		$user = $this->user;
		
		if ($user['pay_code']) {
			$this->ApiResult(false,10001,'已设置');
		}

		$res = $this->UserService->updateUser(['user_id' => $this->user_id],['pay_code' => password_hash($pay_password,PASSWORD_DEFAULT)]);
		if (false !== $res) {
			$this->ApiResult(true,10000,'设置成功');
		} else {
			$this->ApiResult(false,10001,'设置失败');
		}
	}
	/**
	 * 修改支付密码
	 */
	public function editPayPassword()
	{
		$old_pay = input('old_pay');
		$pay_password = input('pay_password');
		$second_password = input('second_password');

		if (!preg_match("/^\d{6}$/", $pay_password)) {
			$this->ApiResult(false,10001,'请输入6位支付密码');
		}
				
		if ($pay_password !== $second_password) {
			$this->ApiResult(false,10001,'两次新密码必须一样');
		}

		$user = $this->user;
		if (!password_verify($old_pay,$user['pay_code'])) {
			$this->ApiResult(false,10001,'旧密码错误');
		}

		$res = $this->UserService->updateUser(['user_id' => $this->user_id],['pay_code' => password_hash($pay_password,PASSWORD_DEFAULT)]);
		if (false !== $res) {
			$this->ApiResult(true,10000,'修改成功');
		} else {
			$this->ApiResult(false,10001,'修改失败');
		}
	}
	/**
	 * 忘记支付密码
	 */
	public function forgetPayPassword()
	{
		$forget_cache = input('forget_cache');//进行第二步验证的缓存
		$RegisterService = new RegisterService();

    	if (empty($forget_cache)) {//操作第一步

    		$mobile    = input('mobile');
    		$code      = input('code');
    		$iden_card = input('iden_card');
			if(!preg_match("/^1[34578]\d{9}$/", $mobile)){
				$this->ApiResult(false,10001,'手机格式错误');
			}
			//验证身份证
    		$user = $this->user;
    		if (empty($user['iden_card'])) {
    			$this->ApiResult(false,10001,'请先绑定身份证');
    		}
    		if ($user['iden_card'] != $iden_card) {
    			$this->ApiResult(false,10001,'身份非该用户绑定的');
    		}
    		if ($user['user_name'] != $mobile) {
    			$this->ApiResult(false,10001,'手机非该用户绑定');
    		}
			//验证验证码
    		$checkCode = $RegisterService->checkCode($mobile,$code,$type=3);
    		if ($checkCode['status'] !== true) {
    			$this->ApiResult(false,10001,$checkCode['msg']);
    		}

    		cache($checkCode['key'],$mobile,3600);//存入缓存为了第二步
    		$this->ApiResult(true,10000,$checkCode['msg'],['forget_cache' => $checkCode['key']]);
    	} else {

    		$mobile = cache($forget_cache);//通过缓存获取手机号码
    		if (empty($mobile)) {//操作过期
    			$this->ApiResult(false,10002,'操作过期');
    		}
    		$pay_password = input('pay_password');
    		$second_password = input('second_password');

    		if (!preg_match("/^\d{6}$/", $pay_password)) {
				$this->ApiResult(false,10001,'请输入6位支付密码');
			}
			if ($pay_password !== $second_password) {
				$this->ApiResult(false,10001,'两次密码不一致');
			}

			$res = $this->UserService->updateUser(['user_id' => $this->user_id],['pay_code' => password_hash($pay_password,PASSWORD_DEFAULT)]);
			if (false !== $res) {
				$this->ApiResult(true,10000,'修改成功');
			} else {
				$this->ApiResult(false,10001,'修改失败');
			}
    	}
	}
	/**
	 * 退出登录
	 */
	public function logout()
	{
		$res = $this->UserService->updateUser(['user_id' => $this->user_id],['token' => '']);
		if (false !== $res) {
			$this->ApiResult(true,10000,'退出成功');
		} else {
			$this->ApiResult(false,10001,'退出失败');
		}
	}
	/**
	 * 修改登录密码
	 */
	public function editPassword()
	{
		$old_password = input('old_password');
		$password = input('password');
		$second_password = input('second_password');

		if (empty($old_password) || empty($password) || empty($second_password)) {
			$this->ApiResult(false,10001,'请输入登录密码');
		}

		if (!preg_match("/^(\w*(?=\w*\d)(?=\w*[A-Za-z])\w*){6,16}$/", $password)) {
			$this->ApiResult(false,10001,'密码要6-16（英文/数字/符号）至少两种或下划线组合');
		}
		if ($password !== $second_password) {
			$this->ApiResult(false,10001,'两次新密码必须一样');
		}

		$user = $this->user;
		if (!password_verify($old_password,$user['password'])) {
			$this->ApiResult(false,10001,'旧密码错误');
		}

		$res = $this->UserService->updateUser(['user_id' => $this->user_id],['password' => password_hash($password,PASSWORD_DEFAULT),'token' => '']);
		if (false !== $res) {
			$this->ApiResult(true,10000,'修改成功');
		} else {
			$this->ApiResult(false,10001,'修改失败');
		}
	}
	/**
	 * 修改昵称
	 */
	public function editNickname()
	{
		$nickname = input('nickname');
		if (empty($nickname)) {
			$this->ApiResult(false,10001,'参数错误');
		}

		$exist = $this->UserService->getUser(['nick_name' => $nickname],'user_id');

		if (!empty($exist)) {//判断昵称是否存在
			$this->ApiResult(false,10001,'昵称已经存在');
		}

		$res = $this->UserService->updateUser(['user_id' => $this->user_id],['nick_name' => $nickname]);
		if (false !== $res) {
			$this->ApiResult(true,10000,'修改成功');
		} else {
			$this->ApiResult(false,10001,'修改失败');
		}
	}

    /**
     * 银行卡列表
     */
	function cardLists(){
        $lists = Db::name('credit')->field('credit_id,user_id,credit_num,credit_name,credit_iden_num,credit_deposit,company')->where('user_id = "'.$this->user_id.'" and is_del = 1')->select();
        $lists = $lists->all();
        foreach ($lists as $k=>$vo){
            $lists[$k]['company'] = $vo['company'] ? $vo['company'] : '';
        }
        $this->ApiResult(true,10000,'操作成功',$lists);
    }

	/**
	 * 添加银行卡
	 */
	public function addCard()
	{
		$data = input('post.');
		$CardValidate = new CardValidate();
		$result = $CardValidate->check($data);
		if (true !== $result) {
			$this->ApiResult(false,10001,$CardValidate->getError());
		}
		//判断该用户是否已经实名过
		$user = $this->user;
		if ($user['iden_card']) {//实名过了要添加
			
			if ($data['credit_iden_num'] != $user['iden_card']) {
				$this->ApiResult(false,10001,'该身份证与您绑定的身份证有冲突');
			}
			//判断银行卡是否正确
			// $checkCard = $this->UserService->checkCard($data['credit_name'],$data['credit_num'],$data['credit_iden_num'],$data['credit_mobile']);
			// if ($checkCard->resp->desc != 'OK') {
			// 	$this->ApiResult(false,10001,$checkCard->resp->desc);
			// }
			$data['create_time'] = time();
			$data['user_id'] = $this->user_id;
			// $data['company'] = $checkCard->data->bank_name;
			$data['company'] = '写死的银卡';
			$res = $this->UserService->addCard($data);
			if (false !== $res) {
				$this->ApiResult(true,10000,'添加成功',$data);
			} else {
				$this->ApiResult(false,10001,'添加失败');
			}
		} else {
			//判断身份是否已经绑定
			$idcard = $this->UserService->getUser(['iden_card' => $data['credit_iden_num']], 'user_id');
			if ($idcard) {//身份证已经绑定
				$this->ApiResult(false,10001,'该身份证已经被绑定');
			}
			// //判断银行卡是否正确
			// $checkCard = $this->UserService->checkCard($data['credit_name'],$data['credit_num'],$data['credit_iden_num'],$data['credit_mobile']);
			// if ($checkCard->resp->desc != 'OK') {
			// 	$this->ApiResult(false,10001,$checkCard->resp->desc);
			// }

			Db::startTrans();
			try {
				//添加银行卡
				$data['create_time'] = time();
				$data['user_id'] = $this->user_id;
				// $data['company'] = $checkCard->data->bank_name;
				$data['company'] = '写死的银卡';
				$this->UserService->addCard($data);
				$this->UserService->updateUser(['user_id' => $this->user_id],['iden_card' => $data['credit_iden_num'],'certification' => 1]);
				Db::commit();
				$this->ApiResult(true,10000,'实名成功',$data);
			} catch (Exception $e) {
				Db::rollback();
				$this->ApiResult(false,10001,'实名认证失败');
			}
		}
	}



	/**
	 * 删除银行卡
	 */
	public function deleteCard()
	{
		$ids = input('ids');
		if (empty($ids)) {
			$this->ApiResult(false,10001,'请选择要删除的银行卡');
		}

		$res = $this->UserService->deleteCard(['user_id' => $this->user_id, 'credit_id' => ['in',$ids]]);
		if (false !== $res) {
			$this->ApiResult(true,10000,'删除成功');
		} else {
			$this->ApiResult(false,10001,'删除失败');
		}
	}
	/**
	 * 获取个人中心信息
	 */
	public function index()
	{
		$user_info = $this->user;
		unset($user_info['password']);
		unset($user_info['first_leader']);
		unset($user_info['second_leader']);
		unset($user_info['iden_card']);
		$user_info['level_name'] = config('member_level')[$user_info['level']];
		
		$order_count = $this->UserService->orderCount(['user_id' => $this->user_id]);

		$this->ApiResult(true,10000,'获取成功',['user_info' => $user_info,'order_count' => $order_count]);
	}
	/**
	 * 充值
	 */
	public function recharge()
	{
		$money = input('money');
		$type = input('type/d');
		if (!preg_match("/^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/", $money)) {
			$this->ApiResult(false,10001,'请输入正确的金额');
		}
		if ($type == 1) {//微信支付
			$res = $this->UserService->recharge($money,1,$this->user_id);
			if (false !== $res['status']) {

				// $this->UserService->WxPay($res['order_sn'], $money);
				$this->WxCallback($res['order_sn']);//先做一个回调
				$this->ApiResult(true,10000,'支付成功');
			} else {

				$this->ApiResult(false,10001,'支付失败');
			}

		} elseif($type == 2) {//支付宝

		} else {
			$this->ApiResult(false,10001,'其他支付暂未开通');
		}
		
	}
	/**
	 * 微信支付回调
	 */
	public function WxCallback($order_sn)
	{
		$order = Db::name('recharge')->field('id,money,user_id')->where('order_sn', $order_sn)->find();
		$money = $order['money'];
		$user_id = $order['user_id'];
		$id = $order['id'];
		if (empty($money)) {
			return false;
		} else {
			Db::name('recharge')->where('order_sn',$order_sn)->update(['status' => 2, 'pay_time' => time(),'transaction_id' => 1111]);
			Db::name('balance_record')->insert(['money' => $money, 'scene' => 1, 'sign' => 1, 'create_time' => time(), 'user_id' => $user_id, 'remarks' => '微信充值', 'data_id' => $id]);
			Db::name('shop_user')->where('user_id',$user_id)->setInc('balance',$money);
		}
	}
	/**
	 * 申请合伙人
	 */
	public function applyPartner()
	{
		$user = $this->user;

		$address_id = input('address_id/d');
		$user_name = input('user_name');
		$mobile = input('mobile');
		if (empty($address_id)) {
			$this->ApiResult(false,10001,'请选择地址');
		}
		if (empty($user_name)) {
			$this->ApiResult(false,10001,'请输入名字');
		}
		if (empty($mobile) || !preg_match("/^1[34578]\d{9}$/", $mobile)) {
			$this->ApiResult(false,10001,'手机号码错误');
		}
		switch ($user['level']) {
			case '2'://申请区代理

				//判断申请资格
				//获取下一级的数量
				// $low_level_count = $this->UserService->lowLevelNum($this->user_id,2);
				// if ($low_level_count<10) {
				// 	$this->ApiResult(false,10001,'您要直推10个铂金会员，才有申请资格');
				// }
				//判断是否申请中
				$info = $this->UserService->applyPartner(['user_id' => $this->user_id, 'status' => 1, 'apply_level' => 3]);			
				if ($info) {
					$this->ApiResult(false,10001,'您已经申请');
				}
				//判断地区是否已经被申请
				$address = $this->UserService->getAddress(['id' => $address_id, 'level' => 3]);
				
				if (empty($address['id']) || $address['user_id'] > 0) {
					$this->ApiResult(false,10001,'该地址已经被申请');
				}

				$res = $this->UserService->addPartner(['user_id' => $this->user_id, 'apply_level' => 3, 'create_time' => time(), 'address_id' => $address_id, 'user_name' => $user_name, 'mobile' => $mobile]);
				
				break;
			case '3'://申请市代理

				//判断申请资格
				//获取下一级的数量
				// $low_level_count = $this->UserService->lowLevelNum($this->user_id,3);
				// if ($low_level_count<5) {
				// 	$this->ApiResult(false,10001,'您要直推5个区级合伙人，才有申请资格');
				// }
				//判断是否申请中
				$info = $this->UserService->applyPartner(['user_id' => $this->user_id, 'status' => 1, 'apply_level' => 4]);			
				if ($info) {
					$this->ApiResult(false,10001,'您已经申请');
				}
				//判断地区是否已经被申请
				$address = $this->UserService->getAddress(['id' => $address_id, 'level' => 2]);
				
				if (empty($address['id']) || $address['user_id'] > 0) {
					$this->ApiResult(false,10001,'该地址已经被申请');
				}

				$res = $this->UserService->addPartner(['user_id' => $this->user_id, 'apply_level' => 4, 'create_time' => time(), 'address_id' => $address_id, 'user_name' => $user_name, 'mobile' => $mobile]);

				break;
			case '4'://申请省代理

				//获取下一级的数量
				// $low_level_count = $this->UserService->lowLevelNum($this->user_id,4);
				// if ($low_level_count<5) {
				// 	$this->ApiResult(false,10001,'您要直推5个市级合伙人，才有申请资格');
				// }
				//判断是否申请中
				$info = $this->UserService->applyPartner(['user_id' => $this->user_id, 'status' => 1, 'apply_level' => 5]);			
				if ($info) {
					$this->ApiResult(false,10001,'您已经申请');
				}
				//判断地区是否已经被申请
				$address = $this->UserService->getAddress(['id' => $address_id, 'level' => 1]);
				if (empty($address['id']) || $address['user_id'] > 0) {
					$this->ApiResult(false,10001,'该地址已经被申请');
				}

				$res = $this->UserService->addPartner(['user_id' => $this->user_id, 'apply_level' => 5, 'create_time' => time(), 'address_id' => $address_id, 'user_name' => $user_name, 'mobile' => $mobile]);

				break;
			default:

				$this->ApiResult(false,10001,'会员等级过低无法申请');
				break;
		}
		if (false !== $res) {
			$this->ApiResult(true,10000,'申请成功');
		} else {
			$this->ApiResult(false,10001,'申请失败');
		}
	}
	/**
	 * 获取代理地区地址
	 */
	public function partnerAddress()
	{
		$user = $this->user;
		if ($user['level'] < 2) {
			$this->ApiResult(false,10001,'您为满足申请条件');
		}

		$list = $this->UserService->partnerAddress($user['level']);

		$this->ApiResult(true,10000,'获取成功',$list);
	}
	/**
	 * 撤销合伙人
	 */
	public function revokePartner()
	{
		$pn_id = input('pn_id/d');
		if (empty($pn_id)) {
			$this->ApiResult(false,10001,'参数错误');
		}

		$res = $this->UserService->revokePartner($pn_id,$this->user_id);

		if (false !== $res['status']) {
			$this->ApiResult(true,10000,'撤销成功');
		} else {
			$this->ApiResult(false,10001,$res['msg']);
		}
	}
	/**
	 * 合伙人申请历史列表
	 */
	public function partnerApplyRecord()
	{
		$page = input('page/d')?input('page/d'):1;
		$size = input('size/d')?input('size/d'):10;

		$list = $this->UserService->partnerApplyRecord($this->user_id,$page,$size);
		$this->ApiResult(true,10000,'获取成功',$list);
	}
	/**
	 * 合伙人申请列表条数
	 */
	public function applyRecordCount()
	{
		$count = $this->UserService->applyRecordCount($this->user_id);
		
		$this->ApiResult(true,10000,'获取成功',$count);
	}
	/**
	 * 合伙人下级统计
	 */
	public function partnerDetail()
	{
		$user    = $this->user;
		$user_id = $this->user_id;
		if ($user['level'] < 3) {
			$this->ApiResult(false,10001,'您没有查看资格');
		}
		$page = input('page/d')?input('page/d'):1;
		$size = input('size/d')?input('size/d'):10;
		//获取代理商列表
		$list = $this->UserService->agentList($user_id,$page,$size);
		
		$count = $this->UserService->countPaneter($this->user_id);

		$this->ApiResult(true,10000,'获取成功',['money_count' => (float)$count, 'list' => $list]);
	}
	/**
	 * 申请合伙人列表
	 */
	public function applyPartnerList()
	{
		$res = $this->UserService->applyList($this->user_id);
		$this->ApiResult(true,10000,'获取成功',$res);
	}
	/**
	 * 钱包明细
	 */
	public function balanceDetail(){
		$page = input('page/d')?input('page/d'):1;
		$size = input('size/d')?input('size/d'):10;
		$list = Db::name('balance_record')
		      ->where('user_id',$this->user_id)
		      ->limit(($page-1)*$size, $size)
		      ->order('id desc')
		      ->select()
		      ->toArray();
		$total = Db::name('balance_record')
		       ->where('user_id',$this->user_id)
		       ->count();
		$data = array();
		$status = [
            '1' => '提现',
            '2' => '充值',
            '3' => '退款',
            '4' => '消费',
            '5' => '奖励'
		];
		if($list){
			foreach ($list as $k => $v) {
				if($v['sign'] == 1){
					$type = '+';
				}else{
					$type = '-';
				}
				$data[$k]['id']     = $v['id'];
				$data[$k]['status'] = $status[$v['scene']];
				$data[$k]['time']   = $v['create_time'];
				$data[$k]['balance']= $v['money'];
				$data[$k]['money']  = $type.$v['money'];
				$data[$k]['sign']   = $v['sign'];
			}
		}
		$row = [
          'total'  => $total,
          'data'   => $data
		];
		$this->ApiResult(true,10000,'获取成功',$row);
	}



	/**
	 * 明细详情
	 */
	public function detailInfo(){
		$id =  input('id');
		$info = Db::name('balance_record')->where('id',$id)->find();
		$data = array();
		$payment_type = [
			
	        '1'        => '余额支付',
	        '2'        => '微信支付',
	        '3'        => '支付宝支付'
		];

		if($info['scene'] > 2 && $info['scene'] < 6){

			$order = Db::name('order')->where('order_id',$info['data_id'])->find();
			$data['money'] = $info['money'];
			$data['order_no'] = $order['order_no'];
			$data['goods_name'] = $order['goods_name'];
			$data['number'] = $order['number'];
			$data['payment_type'] = $payment_type[$order['payment_type']];
			$data['type'] = $info['remarks'];
			$data['time'] = $info['create_time'];
		} elseif($info['scene']== 2) {//充值
			$pay_type = ['后台充值','微信','支付宝'];
			$recharge = Db::name('recharge')->where('id',$info['data_id'])->find();
			$data['money'] = $recharge['money'];
			$data['order_no'] = $recharge['order_sn'];
			$data['type'] = $info['remarks'];
			$data['time'] = date('Y-m-d H:i:s',$recharge['pay_time']);
			$data['payment_type'] = $pay_type[$recharge['type']];

		} elseif($info['scene']== 1) {
			$cash_record = Db::name('cash_record')->alias('a')->field('a.money,a.fee_money,a.create_time,a.order_sn,b.credit_num,b.company')
							->join('credit b', 'a.card_id=b.credit_id')->where('a.id',$info['data_id'])->find();
			$data['money'] = $cash_record['money'];
			$data['fee_money'] = $cash_record['fee_money'];
			$data['order_no'] = $cash_record['order_sn'];
			$data['company'] = $cash_record['company'];
			$data['type'] = '余额提现';
			$data['credit_num'] = $cash_record['credit_num'];
			$data['start_time'] = date('Y-m-d H:i:s',$cash_record['create_time']);
			$data['end_time'] = $info['create_time'];
		}
		$this->ApiResult(true,10000,'获取成功',$data);
	}
	/**
	 * 二维码链接
	 */
	public function qrcode_url()
	{
		$user = $this->user;
		$url = 'http://47.107.243.64:8001/user/web/register/mobile/'.$user['user_name'];
		$this->ApiResult(true,10000,'获取成功',$url);
	}
	/**
	 * 获取代理地址名
	 */
	public function partnerAddressName()
	{
		$user = $this->user;
		if ($user['level']<3) {

			$this->ApiResult(true,10000,'获取成功',[]);
		} else {

			$level_address = $this->UserService->partnerAddressName($user['user_id'],$user['level']);
			$this->ApiResult(true,10000,'获取成功',$level_address);
		}
	}
}